var express = require('express');
var router = express.Router();
const dbconfig =require('../util/dbconfig')
var moment =require('moment')

/* GET home page. */
router.get('/', function(req, res, next) {
  var username = req.session.username
  var page = req.query.page || 1
  var info = {
    total:0,  //总共有多少页
    curpage:page,
    list:[] //当前页的文章列表
  }
  var pageSize =2

  let sql ='select  * from  article '
  let sqlArr = []
  let callBack = (err,data)=>{
    if(err){
      console.log(err);
    }else{
      info.total = Math.ceil(data.length / pageSize)
      //查询当前页的文章列表
      let sql ='select  * from  article order by id desc  limit ?,? '
      let sqlArr = [ (info.curpage - 1) * pageSize ,pageSize]
      let callBack2 = (err,data)=>{
        if(data.length===0){
          res.redirect('/?page='+((page-1)|| 1))
        }else{
          if(err){
            console.log(err);
          }else{
            info.list = data 
            // console.log(info.list);
            res.render('index',{username:username,data:info})
          }
        }
       
      }
      dbconfig.sqlConnect(sql,sqlArr,callBack2);
    }
  }
  dbconfig.sqlConnect(sql,sqlArr,callBack);
});

//渲染注册页
router.get('/regist',(req,res,next)=>{
  res.render('regist',{})
})

//渲染登录页
router.get('/login',(req,res,next)=>{
  res.render('login',{})
})

//渲染写文章页面
router.get('/write',(req,res,next)=>{
  var username = req.session.username
  var {id,page} = req.query
  var item ={
    title:'',
    content:''
  }
  if(id){
  let sql ='select  * from  article where id=? '
  let sqlArr = [id]
  let callBack = (err,data)=>{
      if(err){
        console.log('查询失败');
      }else{
        item=data
        item['page']=page
        res.render('write',{username:username,item:item})
    }  
  }
  dbconfig.sqlConnect(sql,sqlArr,callBack);
  }else{
    res.render('write',{username:username,item:null})
  }
})

//文章详情页
router.get('/detail',(req,res,next)=>{
  var id = req.query.id
  let sql = "select * from article where id = ?"
  let sqlArr = [id]
  var item = {
    title:"",
    username:"",
    id:'',
    content:''
  }
  let callback=(err,data)=>{
    if(err){
      console.log('查看失败');
    }else{
      console.log('查看成功');
      item = data
      console.log(item);
      res.render('detail',{item:item})
    }
  }
  dbconfig.sqlConnect(sql,sqlArr,callback);
  
})

module.exports = router;
